package top.banner.usercenter.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;
import top.banner.usercenter.auth.CheckLogin;
import top.banner.usercenter.domain.dto.user.JwtTokenRespDTO;
import top.banner.usercenter.domain.dto.user.LoginRespDTO;
import top.banner.usercenter.domain.dto.user.UserLoginDTO;
import top.banner.usercenter.domain.dto.user.UserRespDTO;
import top.banner.usercenter.domain.entity.user.User;
import top.banner.usercenter.service.user.UserService;
import top.banner.usercenter.utils.JwtOperator;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

/**
 * @author XGL
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private WxMaService wxMaService;
    @Resource
    private JwtOperator jwtOperator;

    @GetMapping("/{id}")
    @CheckLogin
    public User findById(@PathVariable Integer id) {
        log.info("我被请求了......");
        return userService.findById(id);
    }

    @PostMapping("/login")
    public LoginRespDTO login(@RequestBody UserLoginDTO loginDTO) throws WxErrorException {
        final WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(loginDTO.getCode());

        //微信openId
        final String openid = result.getOpenid();

        final User user = userService.login(loginDTO, openid);

        //颁发token
        final String token = jwtOperator.generateToken(new HashMap<String, Object>() {{
            put("id", user.getId());
            put("wxNickname", user.getWxNickname());
            put("role", user.getRoles());
        }});

        final Date expiration = jwtOperator.getExpirationDateFromToken(token);
        log.info("用户{}登录成功，生成的token = {},有效期到:{}", loginDTO.getWxNickname(),
                token,
                expiration);

        //构建响应
        return LoginRespDTO.builder()
                .user(new UserRespDTO(user.getId(), user.getAvatarUrl(), user.getBonus(), user.getWxNickname()))
                .token(new JwtTokenRespDTO(token, expiration.getTime()))
                .build();

    }
}
